﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Octopus.Logging
{
    public class LogHelper
    {
        /// <summary>
        /// 防止索引超出下标的获取数组元素方法
        /// </summary>
        private static object GetValue(object[] value, int index)
        {
            if (index < value.Length) { return value[index]; }
            else { return null; }
        }

        private static KeyValuePair<string, object>[] ConvertKVList(object[] values)
        {
            if (values == null || values.Length < 1) { return null; }
            List<KeyValuePair<string, object>> result = new List<KeyValuePair<string,object>>();

            if (values.Length % 2 == 0)
            {
                for (int i = 0; i < values.Length; i += 2)
                {
                    result.Add(new KeyValuePair<string, object>(values[i].ToString(), values[i+1]));
                }
            }
            else
            {
                for (int i = 0; i < values.Length; i += 2)
                {
                    result.Add(new KeyValuePair<string, object>(values[i].ToString(), GetValue(values,i+1)));
                }
            }
            return result.ToArray();
        }

        public static IDictionary<string, object> BuildContext(params object[] values)
        {
            return JoinContext(null, ConvertKVList(values));
        }

        public static IDictionary<string, object> JoinContext(IDictionary<string, object> source, params KeyValuePair<string, object>[] values)
        {
            if (values == null && source == null) { return null; }

            IDictionary<string, object> result = source == null ? new Dictionary<string, object>() : source;

            if (values == null || values.Length < 1) { return result; }
           
            foreach (KeyValuePair<string, object> item in values)
            {
                result.Add(item);
            }

            return result;
        }
    }
}
